<template>
  <div class="app-container">
    <el-card>
      <tree-tools 
        :treeNode="{ name: '公司组织架构', managerName: '负责人', id: '' }" 
        :isRoot="true" 
        @addClick="addDepartment">
      </tree-tools>

      <!-- expand-on-click-node="false 设置只点击下箭头才展开 -->
      <el-tree :data="departs" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current >
        <tree-tools 
          slot-scope="{ data }" 
          :treeNode="data" 
          @delClick="getDepartments" 
          @addClick="addDepartment"
          @updClick="updDepartment">
        </tree-tools>
      </el-tree>
    </el-card>
    <!-- 添加或编辑部门的弹出框 -->
    <AddDepartment 
      ref="addDept"
      :title="title"
      :dialogVisible.sync="dialogVisible" 
      :department="department"
      @confirmClick="confirmClick">
    </AddDepartment>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools'
import AddDepartment from './components/add-department'
import { getDepartments } from '@/api/departments'
import { translateToTreeList } from '@/utils/index'

export default {
  name: "DepartmentsIndex",
  components: {
    TreeTools,
    AddDepartment
  },
  data() {
    return {
      departs: [], // 部门列表
      defaultProps: { // tree规则
        label: 'name',
        children: 'children'
      },
      title: '新增部门', // 弹层的标题
      dialogVisible: false, //控制弹层显示
      department: {} //当前部门
    }
  },
  methods: {
    // 获取部门列表
    async getDepartments() {
      const results = await getDepartments()
      // 将扁平化数据转为树形
      this.departs = translateToTreeList(results, 0)
    },
    // 弹出新增部门弹层
    addDepartment(department) {
      this.title = '新增部门'
      this.department = department
      this.dialogVisible = true
    },
    // 弹出编辑部门弹层
    updDepartment(department) {
      this.title = '编辑部门'
      this.department = department
      // 在父组件里给子组件的data（form）数据赋值
      this.$refs.addDept.form = department
      this.dialogVisible = true
    },
    // 新增或编辑成功
    confirmClick() {
      // 刷新数据，并关闭弹层
      this.getDepartments()
      this.dialogVisible = false
    }
  },
  created() {
    this.getDepartments()
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .el-card {
    padding: 0 100px;

    ::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      background-color: rgba(64, 158, 255, 0.5) !important;
    }
  }
}
</style>